package com.estronger.shopmanage.ui.install.pg;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.adapter.tasking.PgInstallDetailListAdapter;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B34BuildDetailGoods;
import com.estronger.shopmanage.bean.BeanBase;
import com.estronger.shopmanage.bean.InstallDPG;
import com.estronger.shopmanage.bean.ReturnMsgEntity;
import com.estronger.shopmanage.manager.DataManager;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.send.pg.DeliverPGActivity;
import com.estronger.shopmanage.utils.DateUtils;
import com.estronger.shopmanage.utils.JsonUtil;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.estronger.shopmanage.utils.PrefUtils;
import com.estronger.shopmanage.view.AppDialog;
import com.estronger.shopmanage.view.CustomListView;
import com.estronger.shopmanage.view.SelectPeopleActivity;
import com.estronger.shopmanage.view.picker.DateTimePicker;
import com.lidroid.xutils.http.RequestParams;
import com.soonfor.evaluate.tools.Tokens;
import com.soonfor.systemcodes.SystemCodePresenter;
import com.soonfor.systemcodes.SystemCodes;

import java.util.Date;
import java.util.HashMap;

import cn.jesse.nativelogger.NLogger;

import static com.estronger.shopmanage.manager.DataManager.isCondMap;
import static com.estronger.shopmanage.manager.DataManager.isItemMap;
import static com.estronger.shopmanage.manager.DataManager.selectedCondMap_I;
import static com.estronger.shopmanage.manager.NetManager.PG_MS_CONDTION_SURE;

/**
 * （安装）预约派工
 * Created by Soonfor on 2017/5/17.
 */

public class InstallAffirmPGActivity extends BaseActivity implements
        View.OnClickListener {

    private Activity mActivity;
    private View rootView;//根目录View
    private ScrollView sv_root;
    private InstallDPG.Datas.InstallDPGListData itemData;
    private String installid;
    private RelativeLayout rlfMsYyTime, rlfMsDesigner;//预约测量时间、选择设计师
    private TextView tv_title, tvfName, tvfAddress, /*tvfSales,*/ tvfReRemark,
            tvfOrderTimeT, tvfOrderTime, tvfInstallYyTime, tvfInstallaster;
    private ImageView ivfCallToCustomer, ivfSendToCustomer/*, ivfCallToSales, ivfSendToSales*/;
    private EditText etfRemark;//初步沟通输入框
    private String cstName, cstphoneNumber, salesName, salesphoneNumber;
    private CustomListView goodsListView;
    private FloatingActionButton fab;//进入查看设计师形成的悬浮按钮
    private Dialog dialog;
    private boolean isBackBtn;//是否是在点击了返回按钮后弹出dialog
    private boolean isSuccessful = false;//派工是否成功
    private String Communication = "";//初步沟通的内容
    private String fAppointmentDate = "";//预约时间
    private LinearLayout llfSales;//导购相关

    @Override
    protected void init() {
        itemData = (InstallDPG.Datas.InstallDPGListData) getIntent().getSerializableExtra("InstallItem");
        if(itemData != null){
            installid = itemData.dlvid;
            if(selectedCondMap_I !=null &&selectedCondMap_I.size()>0){
                isCondMap = selectedCondMap_I.get(installid);
            }
            if(isCondMap==null){isCondMap = new HashMap<>();}
        }
    }

    @Override
    public void onBackViewClick(View view) {
        if(isChanged()) {
            dialog = AppDialog.createEjectNoticeDialog(mActivity, this);
            isBackBtn = true;
            dialog.show();
        }else{
            mActivity.finish();
        }
    }

    @Override
    protected void initView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mActivity = InstallAffirmPGActivity.this;
        rootView = View.inflate(mActivity, R.layout.activity_pg_install_affirmyupg, null);
        setContentView(rootView);
        tv_title = (TextView) findViewById(R.id.ab_title);
        tv_title.setText("预约派工");
        sv_root = (ScrollView) findViewById(R.id.detail_pgscroller);
        RequestParams params = new RequestParams();
        params.addBodyParameter("sf_action", "getistinfo");
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("dlvid", installid);
        connect(params, NetManager.DETAIL);
        fab = (FloatingActionButton) findViewById(R.id.fab);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mActivity.startActivity(new Intent(mActivity, InstallPGTripActivity.class));
            }
        });
        findViewAndSetEvent(sv_root);
        goodsListView.setFocusable(false);
        initSystemCode();
    }

    //初始取系统参数
    private boolean ifMultSelPeople = false;//选中派工人员是否可以多选
    private void initSystemCode() {
        if (SystemCodes.getInstance().getCRM_DlvIstManCanSelMore().equals("")) {
            new SystemCodePresenter(new SystemCodePresenter.CallBack() {
                @Override
                public void onSingle(int type, boolean isSuccess, String data, String fullmsg) {
                    if (type == 102){
                        if(isSuccess && data != null && data.equals("1")) {
                            SystemCodes.getInstance().setCRM_DlvIstManCanSelMore("1");
                            ifMultSelPeople = true;
                        }else {
                            SystemCodes.getInstance().setCRM_DlvIstManCanSelMore("0");
                            ifMultSelPeople = false;
                        }
                    }
                }

                @Nullable
                @Override
                public void onMult(boolean isSuccess, String fullmsg) {

                }
            }).getOneSystemParams(Tokens.DSM_IFSHOWOTHERPOINT, 102, 0);
        }else {
            if (SystemCodes.getInstance().getCRM_DlvIstManCanSelMore().equals("1"))
                ifMultSelPeople = true;
            else
                ifMultSelPeople = false;
        }
    }

    @Override
    protected void initAction() {
        super.initAction();
        setTextContent();
        ivfCallToCustomer.setOnClickListener(this);
        ivfSendToCustomer.setOnClickListener(this);
        rlfMsYyTime.setOnClickListener(this);
        rlfMsDesigner.setOnClickListener(this);
        etfRemark.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        v.getParent().requestDisallowInterceptTouchEvent(true);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                }
                return false;
            }
        });
        etfRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Communication = etfRemark.getText().toString();
            }
        });

    }

    private void findViewAndSetEvent(View root) {
        llfSales = (LinearLayout) root.findViewById(R.id.llfSales);
        llfSales.setVisibility(View.GONE);
        tvfName = (TextView) root.findViewById(R.id.tvfItemTitle);
        tvfAddress = (TextView) root.findViewById(R.id.tvfItemLocation);
        tvfOrderTimeT = (TextView) root.findViewById(R.id.tvfOrderTimeT);
        tvfOrderTime = (TextView) root.findViewById(R.id.tvfOrderTime);

        tvfInstallaster = (TextView) root.findViewById(R.id.tvfMsDesigner);

        ivfCallToCustomer = (ImageView) root.findViewById(R.id.ivfMCall);
        ivfSendToCustomer = (ImageView) root.findViewById(R.id.ivfMSendms);

        rlfMsYyTime = (RelativeLayout) root.findViewById(R.id.rlfMsYyTime);
        rlfMsDesigner = (RelativeLayout) root.findViewById(R.id.rlfMsDesigner);
        tvfInstallYyTime = (TextView) root.findViewById(R.id.tvfMsYyTime);
        etfRemark = (EditText) root.findViewById(R.id.etfRemark);
        goodsListView = (CustomListView) root.findViewById(R.id.cLvfGoods);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivfMSendms:
                if (isRightNumber(cstphoneNumber)) {
                    Uri uri = Uri.parse("smsto:" + cstphoneNumber);
                    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
                    mActivity.startActivity(intent);
                }
                break;
            case R.id.ivfMSendToSales:
                if (isRightNumber(salesphoneNumber)) {
                    Uri uri = Uri.parse("smsto:" + salesphoneNumber);
                    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
                    mActivity.startActivity(intent);
                }
                break;
            case R.id.ivfMCall:
                if (isRightNumber(cstphoneNumber)) {
                    dialog = AppDialog.createDialog(mActivity, cstName, cstphoneNumber, this, installid);
                    dialog.show();
                }
                break;
            case R.id.ok:
                if (isBackBtn) {
                    if(selectedCondMap_I ==null || selectedCondMap_I.get(installid) ==null){
                        isCondMap.clear();
                        isItemMap.clear();
                    }
                    mActivity.finish();
                } else {
                    try {
                        if (PermissionUtils.isCallPhoneGranted(mActivity)) {
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
                                    + salesphoneNumber));
                            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            mActivity.startActivity(intent);
                        } else {
                            PermissionUtils.ToSetPermissions(mActivity, R.string.PermissionsCallPhone);
                        }
                    } catch (Exception e) {
                        NLogger.e("" + e.getMessage());
                    }
                }
                dialog.dismiss();
                break;
            case R.id.rlfMsYyTime:
                DateUtils.onYearMonthDayTimePicker(mActivity, 15, "预约时间", dateTimeListener);
                break;
            case R.id.rlfMsDesigner:
                SelectPeopleActivity.open(mActivity, 3, installid, ifMultSelPeople);
                break;
        }
    }

    /**
     * 当前activity请求网络成功的回调
     *
     * @params code 各个接口返回的唯一识别码，用来判断是哪个接口成功返回
     * @params result 网络请求成功返回的数据
     */
    @Override
    protected void onNetSuccess(int code, String result) {
        super.onNetSuccess(code, result);
        if (NetManager.DETAIL == code) {
            showCompleshView(result);
        }
        if(PG_MS_CONDTION_SURE == code){
            ReturnMsgEntity reEntity = JsonUtil.returnMsgEntity(result);
            if (reEntity.getSuccess() && reEntity.getMsgcode()==0) {
                try{
                    selectedCondMap_I.remove(installid);
                }catch (Exception e){}
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mActivity.finish();
                    }
                }, 2000);
                AppDialog.showTaskingDialog(mActivity, R.drawable.send_success, "任务派送成功").show();
            } else {
                String msg = reEntity.getMsg();
                if(msg.equals("")) msg = "任务派送失败";
                AppDialog.showTaskingDialog(mActivity, R.drawable.send_failure, msg).show();
            }
        }
    }
    //本Activity请求数据
    public void showCompleshView(String result) {

        B34BuildDetailGoods detail = gson.fromJson(result, B34BuildDetailGoods.class);
        B34BuildDetailGoods.DetailGoods pData = detail.data;
        if (pData == null) {
            return;
        }
        PgInstallDetailListAdapter pdAdapter = new PgInstallDetailListAdapter(mActivity, pData.istitem,goodsListView);
        goodsListView.setAdapter(pdAdapter);
    }

    //由上一个Activity带入数据
    private void setTextContent(){
        if(itemData == null){return;}
        if (TextUtils.isEmpty(itemData.cstbuildname)) {
            cstName = itemData.cstname;
        } else {
            cstName = itemData.cstbuildname + "-" + itemData.cstname;
        }
        tvfName.setText(cstName);
        tvfAddress.setText(itemData.address);
        tvfOrderTimeT.setText("预计安装时间:");
        tvfOrderTime.setText(itemData.pidate);
        cstphoneNumber = itemData.cstmobile;
    }

    public void save(View view) {
            if(tvfInstallYyTime.getText().toString() == null ||tvfInstallYyTime.getText().toString().equals("")){
                Toast.makeText(mActivity,"预约安装时间不能为空",Toast.LENGTH_SHORT).show();
                return;
            }
            if(tvfInstallaster.getText().toString()==null||tvfInstallaster.getText().toString().equals("")){
                Toast.makeText(mActivity,"请选择安装师",Toast.LENGTH_SHORT).show();
                return;
            }
        DataManager.setNoSelectItem_Install();
        RequestParams params = new RequestParams();
        params.addBodyParameter("sf_action", "istconfirmcondition");
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("dlvid", installid);
        params.addBodyParameter("ifassigninstallman","1");
        params.addBodyParameter("newpidate",fAppointmentDate);
        params.addBodyParameter("newinstallman",MyApplication.selectID);
        params.addBodyParameter("remark",Communication);
        params.addBodyParameter("dlvitem", DataManager.getJsonByMap2(isItemMap));
        connect(params, PG_MS_CONDTION_SURE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if(isChanged()) {
                dialog = AppDialog.createEjectNoticeDialog(mActivity, this);
                isBackBtn = true;
                dialog.show();
            }else {
                mActivity.finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    //预约时间
    DateTimePicker.OnYearMonthDayTimePickListener dateTimeListener = new DateTimePicker.OnYearMonthDayTimePickListener() {
        @Override
        public void onDateTimePicked(int index, String year) {
            if (index == 0) {
                long nowDate = System.currentTimeMillis();
                Date d = new Date(nowDate);
                String s = year.replace("今天", (DateTimePicker.beforNumDay(d, 0) + DateTimePicker.getWeekOfDate(d, 0 - 1)));
                if (s.length() < 10) {
                    return;
                } else {
                    tvfInstallYyTime.setText(s);
                    fAppointmentDate = DateTimePicker.BackDateToTime(s);
                }
            } else {
                if (year.length() < 10) {
                    return;
                } else {
                    tvfInstallYyTime.setText(year);
                    fAppointmentDate = DateTimePicker.BackDateToTime(year);
                }
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        String name = MyApplication.selectPeople;
        if (name != null) {
            tvfInstallaster.setText(name + "");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.selectID = "";
        MyApplication.selectPeople = "请选择";
    }
    //界面是否有修改
    private boolean isChanged() {
        if ((isItemMap == null || isItemMap.size() == 0)
                &&(tvfInstallYyTime.getText().toString() == null ||tvfInstallYyTime.getText().toString().equals(""))
                && fAppointmentDate.equals("")
                && Communication.equals(""))
        {
            return false;
        }
        return true;
    }
}